package com.th.dom.controller;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.th.dom.domain.T_User;
import com.th.dom.domain.User;
import com.th.dom.domain.UserLog;
import com.th.dom.service.UserLogService;
import com.th.dom.service.UserService;
import com.th.dom.utils.ExcelUtils;
import com.th.dom.websocket.WebSocketServer;

/**
 * @Package:        com.th.dom.controller
 * @ClassName:      UserController
 * @Description:    UserController
 * @Author:         dove
 * @CreateDate:     2018/7/17 15:38
 * @Version:        1.0
 * <p>Copyright: Copyright (c) 2018/7/17</p>
 *
 */
@Controller
@RequestMapping("/user")
public class UserController {
    private final Logger log = LoggerFactory.getLogger(UserController.class);
    //依赖注入
    @Autowired
    private UserService userService;
    @Autowired
    private UserLogService userLogService;
    
    //配置table表
    @Autowired
    private T_User tuser;
/**
     * @Description:    通过用户名查询用户信息
     * @author      dove
     * @return
     * @exception
     * @date        2018/7/17 15:43
     */
    @RequestMapping("/selectUserByName")
    @ResponseBody
    public User selectUserByName(){
        User user = userService.selectUserByName("张三");
        log.info("UserController selectUserByName success----info!");
        log.error("UserController selectUserByName success----error!");
        return user;
    }
    /**
     * 
      * @Description: 进入首页方法()
      * @author      dove
      * @return 
      * @date  2018年7月19日
     */
    @RequestMapping("/login")
    public String homePage() {
    	
    	log.info(">>>>>>>>>>>>>进入登陆页面>>>>>>>"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        return "login";
    }
    /**
     * 
     * @Description: 测试方法()
     * @author      dove
     * @return 
     * @date  2018年7月19日
     */
    @RequestMapping("/addData")
    @ResponseBody
    public String addData(HttpSession session) {
		WebSocketServer.sendInfoToUser(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"：后台主动推送信息", session);
    	log.info(">>>>>>>>>>>>>执行addData>>>>>>>"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
    	return "success";
    }
    /**
     * 
      * @Description: 登录验证 
      * @author      dove
      * @param params
      * @return 
      * @date  2018年7月19日
     */
    @RequestMapping("/index")
    @ResponseBody
    public String index(HttpServletRequest req,HttpSession session) {
    	String username = req.getParameter("username");
    	String password= req.getParameter("password");
    	User user = userService.selectUserByName(username);
    	if(user != null ) {
    		String pwd = user.getPassword();
    		if(password.equals(pwd)) {
    			session = req.getSession();
    			session.setAttribute("user", user);
    			log.info("登陆成功>>>>>>>>>>>>>>>>user:["+JSON.toJSONString(user)+"]");
    			String ip = req.getHeader("x-forwarded-for"); 
    			if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
    			    ip = req.getHeader("PRoxy-Client-IP"); 
    			} 
    			if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
    			    ip = req.getHeader("WL-Proxy-Client-IP"); 
    			} 
    			if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
    			    ip = req.getRemoteAddr(); 
    			} 
    			InetAddress ipAddress =null; 
    			try {
					ipAddress = InetAddress.getLocalHost();
					log.info(">>>>>>>主机名称: " + ipAddress.getHostName()+"ip:"+ip); 
				} catch (UnknownHostException e) {
					log.error("获取主机名称失败",e);
				} 
    			
				UserLog userLog = new UserLog();
				userLog.setComputer(ipAddress+"");
				userLog.setLogin_ip(ip);
				userLog.setOperation("登陆成功>>>>>>>>>>>>>>>>user:["+JSON.toJSONString(user)+"]");
				userLog.setRemark("");
				userLog.setUsername(username);
				userLog.setType(0);
				session.setAttribute("userLog", userLog);
				try {
					int i = userLogService.insertUserLog(userLog);
					if (i > 0) {
						log.info(">>>>>>>添加用户日志信息成功！"); 
					}else {
						log.info(">>>>>>>添加用户日志信息失败！"); 
					}
				} catch (Exception e) {
					log.error("执行插入用户日志记录信息失败",e);
				}
				
    			
    			return "success";
    		}else{
    			log.info(">>>>>>>>>>>>>>>>UserController>>>>>>>>>>>>>密码错误！");
    		}
    	}else{
    		log.info(">>>>>>>>>>>>>>>>UserController>>>>>>>>>>>>>该用户不存在！");
    	}
    	return "error";
    	
    }
    /**
     * 
      * @Description:  登陆到应用首页
      * @author      dove
      * @return 
      * @date  2018年7月20日
     */
    @RequestMapping("/doLogin")
    public String doLogin(){
    	return "index";
    }
    /**
     * 
      * @Description: excel导入解析
      * @author : dove
      * @param request
      * @return 
      * @date  2018年7月20日
     */
    @RequestMapping("/fileUpLoad")
    @ResponseBody
    public String fileUpLoad(HttpServletRequest request){
    	String flag ="error";
    	String message = "";
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile multipartFile = multipartRequest.getFile("files");
		InputStream is = null;
		try {
			is = multipartFile.getInputStream();
		} catch (IOException e2) {
			log.error("获取文件输入流异常：",e2);
		}
		String filename = multipartFile.getOriginalFilename();
		HttpSession session = request.getSession();
		if(is!=null){
			List<Map<String, String>> readXls = null;
			try {
				readXls = ExcelUtils.readXls(is);
				message = "导入excel成功>>>>excel名称："+filename;
				log.info(message);
				insertUserLog(message,1,session);
				flag ="success";
				analysisData(readXls,session);
			} catch (Exception e1) {
				log.error("excel解析异常：",e1);
				return flag;
			}
			
		}
    	return flag;
    } 
    /**
     * 
      * @Description: 
      * @author : dove
      * @param message 记录日志信息
      * @param type  操作类型（0 无，1新增，2修改，3删除，4查询）
      * @param session 
      * @date  2018年7月23日下午6:33:28
     */
    public void insertUserLog(String message,int type,HttpSession session){
    	UserLog userLog = (UserLog) session.getAttribute("userLog");
		userLog.setOperation(message);
		userLog.setType(type);
		log.info(JSON.toJSONString(userLog));
		try {
			int i = userLogService.insertUserLog(userLog);
			if (i > 0) {
				WebSocketServer.sendInfoToUser(message, session);
				log.info(">>>>>>>导入excel成功！"); 
			}else {
				log.info(">>>>>>>导入excel失败！"); 
			}
		} catch (Exception e) {
			log.error("执行插入用户日志记录信息失败",e);
		}
    }
    
    public void queryUserLogByUsername() {
    	
    }
    
    /**
     * 
      * @Description: 对 excel文件生成的数据 进行解析入库
      * @author : dove
      * @param readXls 
      * @date  2018年7月23日下午4:31:39
     */
    public void analysisData(List<Map<String, String>> readXls,HttpSession session){
    	int c = 0;
    	if (readXls != null) {
    		for (int i = 0; i < readXls.size(); i++) {
        		Map<String, String> map = readXls.get(i);
        		if (map != null) {
        			User t = new User();
        			for (String key : map.keySet()) {
        				log.info("id=="+tuser.getId()+"key=="+key);
        				if(key.equals(tuser.getId())){
        					t.setId(Integer.parseInt(map.get(key)));
        				}else if(key.equals(tuser.getAge())) {
        					t.setAge(Integer.parseInt(map.get(key)));
        				}else if(key.equals(tuser.getPassword())) {
        					t.setPassword(map.get(key));
        				}else if(key.equals(tuser.getCustomerid())) {
        					t.setCustomerid(Integer.parseInt(map.get(key)));
        				}else if(key.equals(tuser.getUsername())) {
        					t.setUsername(map.get(key));
        				}
        			}
        			if(t.getUsername() != null) {
        				c += userService.insert(t);
        			}
        		}
    		}
    	}
    	String message = "总共有"+readXls.size()+"条数据，成功往用户表中插入了"+c+"条数据，失败条数为"+(readXls.size()-c);
    	log.info(message);
    	insertUserLog(message,1,session);
    }
    
    
}
